import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
import Qs from "qs";
import { Toast } from "vant";
import { tokenName } from "@/config/setting";
import store from "@/store";
const instance = axios.create({
  //baseURL:process.env.VUE_APP_BASE_URL,
  baseURL: "http://mstore.higuang365.com/LR_CodeDemo/OrderInfo_ScreenShow",

  // baseURL: 'http://localhost:20472/LR_CodeDemo/OrderInfo_ScreenShow',
  // baseURL: 'http://localhost:3001/index',
  timeout: 1000 * 12,
});

//设置post请求头
instance.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8";
//instance.defaults.withCredentials = true;

instance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    if (store.getters["accessToken"]) {
      config.headers["accesstokon"] = store.getters["accessToken"];
      config.headers["accessid"] = store.getters["userid"].F_UserId;
      config.headers["accessflag"] = "1";
    }
    config.data = Qs.stringify(config.data);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
//响应拦截器
instance.interceptors.response.use(
  //请求成功
  (response: AxiosResponse) => {
    // console.log(response);
    const { status, data } = response;
    if (status !== 200) {
      //服务器错误
      Toast(JSON.stringify(status) + data);
      return Promise.reject(data);
    } else {
      //后台错误
      if (data.code == 200) {
        return Promise.resolve(data.data);
      } else {
        Toast(data.info);
        return Promise.reject(data.code);
      }
    }
  },
  //请求失败
  (error: AxiosError) => {
    const { response } = error;
    if (response) {
      // 请求已发出，但是不在2xx的范围
      if (response.status == 401) {
        Toast("请重新登录！");
        return Promise.reject(response);
      }
      Toast(JSON.stringify(response.data));
      return Promise.reject(response);
    } else {
      Toast("连接超时！");
      return Promise.reject(406);
      // 处理断网的情况
    }
  }
);

export default instance;
